"""
管理员头像管理界面
"""
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from users.models import UserProfile
from carbon.models import CarbonFactor
from tasks.models import Task, TaskAssignment
from .cos_utils import cos_uploader
import json


@login_required
def admin_avatar_management(request):
    """
    头像管理界面 - 管理员可以查看和修改用户头像
    GET /xiangsu/admin/avatars/
    """
    # 获取所有用户信息
    user_profiles = UserProfile.objects.select_related('user').all()
    
    users_data = []
    for profile in user_profiles:
        user_info = profile.get_user_info()
        
        # 现在avatar字段已经是HTML格式，直接使用
        # 检查是否有头像（avatar字段包含非空HTML）
        if user_info['avatar'] and '<img' in user_info['avatar']:
            # 已经有头像HTML，直接使用
            avatar_html = user_info['avatar'].replace('width: 100px', 'width: 80px').replace('height: 100px', 'height: 80px')
        else:
            # 没有头像，显示占位符
            avatar_html = '<div style="width: 80px; height: 80px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center; color: #999; border: 2px solid #ddd;">暂无头像</div>'
        
        users_data.append({
            'user_id': profile.user.id,
            'username': user_info['username'],
            'avatar_url': user_info['avatar_url'],  # 使用avatar_url字段获取原始URL
            'avatar_html': avatar_html,
            'nickname': user_info['nickname'],
            'email': user_info['email']
        })
    
    # 生成HTML页面
    html_content = f"""
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>像素应用 - 头像管理</title>
        <style>
            body {{
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 20px;
                background-color: #f5f5f5;
            }}
            .container {{
                max-width: 1200px;
                margin: 0 auto;
                background: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }}
            .header {{
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20px;
                padding-bottom: 15px;
                border-bottom: 1px solid #eee;
            }}
            .header h1 {{
                color: #333;
                margin: 0;
            }}
            .user-list {{
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
                gap: 20px;
            }}
            .user-card {{
                border: 1px solid #ddd;
                padding: 15px;
                border-radius: 8px;
                background: #fafafa;
            }}
            .user-avatar {{
                text-align: center;
                margin-bottom: 10px;
            }}
            .user-info {{
                text-align: center;
            }}
            .user-info h3 {{
                margin: 5px 0;
                color: #333;
            }}
            .user-info p {{
                margin: 3px 0;
                color: #666;
            }}
            .upload-section {{
                background: #f8f9fa;
                padding: 15px;
                border-radius: 5px;
                margin-top: 10px;
                border: 1px dashed #ddd;
            }}
            .upload-btn {{
                background: #007bff;
                color: white;
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                margin-top: 5px;
            }}
            .upload-btn:hover {{
                background: #0056b3;
            }}
            .no-avatar {{
                color: #999;
                font-style: italic;
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>像素应用 - 用户头像管理</h1>
                <div>当前用户: {request.user.username}</div>
            </div>
            
            <div class="user-list">
    """
    
    for user in users_data:
        html_content += f"""
                <div class="user-card">
                    <div class="user-avatar">
                        {user['avatar_html']}
                    </div>
                    <div class="user-info">
                        <h3>{user['username']}</h3>
                        <p>ID: {user['user_id']}</p>
                        <p>昵称: {user['nickname'] or '未设置'}</p>
                        <p>邮箱: {user['email']}</p>
                        <div class="upload-section">
                            <input type="file" id="avatar_{user['user_id']}" accept="image/*" style="display: none;">
                            <button class="upload-btn" onclick="document.getElementById('avatar_{user['user_id']}').click()">
                                上传新头像
                            </button>
                        </div>
                    </div>
                </div>
        """
    
    html_content += """
            </div>
        </div>

        <script>
            console.log('页面加载完成，开始初始化事件监听器');
            
            // 为每个文件输入添加事件监听器
            document.querySelectorAll('input[type="file"]').forEach(input => {
                console.log('为文件输入添加事件监听器:', input.id);
                input.addEventListener('change', function(e) {
                    console.log('文件选择事件触发:', this.id);
                    const file = e.target.files[0];
                    if (file) {
                        console.log('选择的文件:', file.name, file.size, file.type);
                        const userId = this.id.split('_')[1];
                        console.log('用户ID:', userId);
                        uploadAvatar(userId, file);
                    } else {
                        console.log('未选择文件');
                    }
                });
            });

            function uploadAvatar(userId, file) {
                console.log('开始上传头像，用户ID:', userId);
                
                const formData = new FormData();
                formData.append('avatar', file);
                
                // 添加CSRF令牌
                const csrftoken = getCookie('csrftoken');
                console.log('CSRF令牌:', csrftoken ? '已获取' : '未获取');
                
                const url = '/xiangsu/upload/avatar/?user_id=' + userId;
                console.log('请求URL:', url);
                
                fetch(url, {
                    method: 'POST',
                    body: formData,
                    credentials: 'same-origin',
                    headers: csrftoken ? {
                        'X-CSRFToken': csrftoken
                    } : {}
                })
                .then(response => {
                    console.log('服务器响应状态:', response.status, response.statusText);
                    return response.json();
                })
                .then(data => {
                    console.log('服务器响应数据:', data);
                    if (data.success) {
                        alert('头像上传成功！');
                        location.reload();
                    } else {
                        alert('上传失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('上传出错:', error);
                    alert('上传出错: ' + error.message);
                });
            }
            
            // 获取CSRF令牌的函数
            function getCookie(name) {
                let cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    const cookies = document.cookie.split(';');
                    for (let i = 0; i < cookies.length; i++) {
                        const cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) === (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
            
            // 测试函数调用
            console.log('页面初始化完成');
        </script>
    </body>
    </html>
    """
    
    return HttpResponse(html_content)


@login_required
def admin_carbon_factors(request):
    """碳排因子管理界面 - 管理员查看/新增/编辑/删除因子
    GET /xiangsu/admin/carbon/factors/
    """
    if not request.user.is_staff:
        return HttpResponse('<h1>无权限</h1>', status=403)

    q = request.GET.get('q') or ''
    category = request.GET.get('category') or ''
    qs = CarbonFactor.objects.all()
    if category:
        qs = qs.filter(category=category)
    if q:
        qs = qs.filter(item_name__icontains=q)
    qs = qs.order_by('category', 'item_name')

    cats = [c[0] for c in CarbonFactor.CATEGORY_CHOICES]
    rows = []
    for f in qs:
        rows.append({
            'factor_id': f.factor_id,
            'item_name': f.item_name,
            'category': f.category or '',
            'unit': f.unit,
            'emission_per_unit': str(f.emission_per_unit)
        })

    html = [
        "<!DOCTYPE html>",
        "<html lang='zh-CN'>",
        "<head>",
        "<meta charset='UTF-8'>",
        "<meta name='viewport' content='width=device-width, initial-scale=1.0'>",
        "<title>像素应用 - 碳排因子管理</title>",
        "<style>",
        "body{font-family:Arial,sans-serif;background:#f5f5f5;margin:0;padding:20px}",
        ".container{max-width:1200px;margin:0 auto;background:#fff;padding:20px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1)}",
        ".header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:10px;border-bottom:1px solid #eee}",
        ".filters{display:flex;gap:10px;margin-bottom:12px}",
        ".table{width:100%;border-collapse:collapse}",
        ".table th,.table td{border:1px solid #ddd;padding:8px;text-align:left}",
        ".table th{background:#fafafa}",
        ".actions{display:flex;gap:6px}",
        ".btn{padding:6px 10px;border:none;border-radius:4px;cursor:pointer}",
        ".btn.save{background:#28a745;color:#fff}",
        ".btn.delete{background:#dc3545;color:#fff}",
        ".btn.create{background:#007bff;color:#fff}",
        ".top-form{display:flex;gap:8px;margin:12px 0}",
        "</style>",
        "</head>",
        "<body>",
        "<div class='container'>",
        "<div class='header'><h1>碳排因子管理</h1><div>管理员: %s</div></div>" % request.user.username,
        "<div class='filters'>",
        "<input id='q' placeholder='搜索物品名' value='%s'/>" % q,
        "<select id='category'>",
    ]
    html.append("<option value=''>全部分类</option>")
    for c in cats:
        sel = " selected" if c == category else ""
        html.append(f"<option value='{c}'{sel}>{c}</option>")
    html += [
        "</select>",
        "<button class='btn' onclick='applyFilters()'>筛选</button>",
        "</div>",
        "<div class='top-form'>",
        "<input id='new_name' placeholder='物品/行为名称'>",
        "<select id='new_cat'>",
    ]
    for c in cats:
        html.append(f"<option value='{c}'>{c}</option>")
    html += [
        "</select>",
        "<input id='new_unit' placeholder='单位(kg/km/kWh/件)'>",
        "<input id='new_emission' placeholder='每单位排放(数字)'>",
        "<button class='btn create' onclick='createFactor()'>新增因子</button>",
        "</div>",
        "<table class='table'>",
        "<thead><tr><th>ID</th><th>名称</th><th>分类</th><th>单位</th><th>每单位排放</th><th>操作</th></tr></thead>",
        "<tbody>",
    ]
    for r in rows:
        html += [
            f"<tr>",
            f"<td>{r['factor_id']}</td>",
            f"<td><input id='name_{r['factor_id']}' value='{r['item_name']}'/></td>",
            f"<td><select id='cat_{r['factor_id']}'>" + ''.join([f"<option value='{c}' {'selected' if c==r['category'] else ''}>{c}</option>" for c in cats]) + "</select></td>",
            f"<td><input id='unit_{r['factor_id']}' value='{r['unit']}'/></td>",
            f"<td><input id='em_{r['factor_id']}' value='{r['emission_per_unit']}'/></td>",
            f"<td class='actions'><button class='btn save' onclick='saveFactor({r['factor_id']})'>保存</button><button class='btn delete' onclick='deleteFactor({r['factor_id']})'>删除</button></td>",
            f"</tr>",
        ]
    html += [
        "</tbody></table>",
        "</div>",
        "<div style='margin-top:16px;display:flex;gap:8px'>",
        "<button class='btn create' onclick='seedBasic()'>一键导入基础因子</button>",
        "</div>",
        "<script>",
        "function applyFilters(){const q=document.getElementById('q').value;const c=document.getElementById('category').value;location.href='?q='+encodeURIComponent(q)+'&category='+encodeURIComponent(c)}",
        "function createFactor(){const name=document.getElementById('new_name').value.trim();const cat=document.getElementById('new_cat').value;const unit=document.getElementById('new_unit').value.trim();const em=document.getElementById('new_emission').value.trim();if(!name||!unit||!em){alert('请填写完整');return;}fetch('/xiangsu/carbon/factors',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({item_name:name,category:cat,unit:unit,emission_per_unit:em})}).then(r=>r.json()).then(d=>{if(d.success){alert('创建成功');location.reload()}else{alert('失败:'+d.message)}}).catch(e=>alert('错误:'+e))}",
        "function saveFactor(id){const name=document.getElementById('name_'+id).value.trim();const cat=document.getElementById('cat_'+id).value;const unit=document.getElementById('unit_'+id).value.trim();const em=document.getElementById('em_'+id).value.trim();if(!name||!unit||!em){alert('请填写完整');return;}fetch('/xiangsu/carbon/factors',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({item_name:name,category:cat,unit:unit,emission_per_unit:em})}).then(r=>r.json()).then(d=>{if(d.success){alert('保存成功');location.reload()}else{alert('失败:'+d.message)}}).catch(e=>alert('错误:'+e))}",
        "function deleteFactor(id){if(!confirm('确认删除因子 '+id+' ?'))return;fetch('/xiangsu/admin/carbon/factor/delete/',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({factor_id:id})}).then(r=>r.json()).then(d=>{if(d.success){alert('删除成功');location.reload()}else{alert('失败:'+d.message)}}).catch(e=>alert('错误:'+e))}",
        "function seedBasic(){if(!confirm('确认导入常用基础因子？若已存在将被跳过。'))return;fetch('/xiangsu/admin/carbon/factors/seed/',{method:'POST',credentials:'same-origin'}).then(r=>r.json()).then(d=>{if(d.success){alert('导入完成：'+d.count+' 项');location.reload()}else{alert('失败:'+d.message)}}).catch(e=>alert('错误:'+e))}",
        "</script>",
        "</body>",
        "</html>"
    ]
    return HttpResponse(''.join(html))


@csrf_exempt
@require_http_methods(["POST"])
@login_required
def admin_delete_carbon_factor(request):
    """删除因子 - 管理员专用 POST /xiangsu/admin/carbon/factor/delete/ {factor_id}
    """
    if not request.user.is_staff:
        return HttpResponse(json.dumps({'success': False, 'message': '无权限'}), content_type='application/json', status=403)
    try:
        payload = json.loads(request.body or '{}')
        fid = payload.get('factor_id')
        obj = CarbonFactor.objects.filter(factor_id=fid).first()
        if not obj:
            return HttpResponse(json.dumps({'success': False, 'message': '因子不存在'}), content_type='application/json', status=404)
        obj.delete()
        return HttpResponse(json.dumps({'success': True}), content_type='application/json')
    except Exception as e:
        return HttpResponse(json.dumps({'success': False, 'message': str(e)}), content_type='application/json', status=500)

@csrf_exempt
@require_http_methods(["POST"])
@login_required
def admin_seed_carbon_factors(request):
    if not request.user.is_staff:
        return HttpResponse(json.dumps({'success': False, 'message': '无权限'}), content_type='application/json', status=403)
    items = [
        # 交通
        {'item_name': '驾车', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.21'},
        {'item_name': '地铁', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.05'},
        {'item_name': '公交', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.10'},
        {'item_name': '骑行', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.01'},
        {'item_name': '飞机', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.25'},
        {'item_name': '火车', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.06'},
        {'item_name': '高铁', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.07'},
        {'item_name': '摩托车', 'category': '交通', 'unit': 'km', 'emission_per_unit': '0.12'},
        # 餐饮
        {'item_name': '牛肉', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '27.0'},
        {'item_name': '红肉', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '27.0'},
        {'item_name': '猪肉', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '12.0'},
        {'item_name': '禽肉', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '6.0'},
        {'item_name': '主食', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '1.0'},
        {'item_name': '蔬菜', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '1.0'},
        {'item_name': '咖啡奶茶', 'category': '餐饮', 'unit': '杯', 'emission_per_unit': '0.4'},
        {'item_name': '水果', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '1.0'},
        {'item_name': '豆制品', 'category': '餐饮', 'unit': 'kg', 'emission_per_unit': '2.0'},
        # 能源/购物
        {'item_name': '用电', 'category': '能源', 'unit': 'kWh', 'emission_per_unit': '0.58'},
        {'item_name': '空调', 'category': '能源', 'unit': 'h', 'emission_per_unit': '0.50'},
        {'item_name': '衣服', 'category': '购物', 'unit': '件', 'emission_per_unit': '10.0'},
        {'item_name': '天然气', 'category': '能源', 'unit': 'm3', 'emission_per_unit': '2.10'},
        {'item_name': '自来水', 'category': '日常', 'unit': 'm3', 'emission_per_unit': '0.34'},
    ]
    created = 0
    for it in items:
        obj, was_created = CarbonFactor.objects.get_or_create(
            item_name=it['item_name'],
            defaults={'category': it['category'], 'unit': it['unit'], 'emission_per_unit': it['emission_per_unit']}
        )
        if not was_created:
            obj.category = it['category']
            obj.unit = it['unit']
            obj.emission_per_unit = it['emission_per_unit']
            obj.save()
        created += 1 if was_created else 0
    return HttpResponse(json.dumps({'success': True, 'count': created}), content_type='application/json')


@csrf_exempt
@require_http_methods(["POST"])
@login_required
def admin_seed_eco_news(request):
    """初始化首页环保动态默认数据 - 管理员专用 POST /xiangsu/admin/eco/news/seed/"""
    if not request.user.is_staff:
        return HttpResponse(json.dumps({'success': False, 'message': '无权限'}), content_type='application/json', status=403)
    defaults = [
        {
            'title': '城市绿化新进展',
            'content': '本市新增绿化面积达到500公顷，空气质量显著提升',
            'image_url': None,
            'is_published': True,
        },
        {
            'title': '新能源汽车普及',
            'content': '政府推出新政策，鼓励市民购买新能源汽车',
            'image_url': None,
            'is_published': True,
        },
        {
            'title': '垃圾分类新规',
            'content': '新版垃圾分类标准即将实施，市民需提前了解',
            'image_url': None,
            'is_published': True,
        },
    ]
    created = 0
    for item in defaults:
        obj, is_created = EcoNews.objects.get_or_create(title=item['title'], defaults=item)
        if is_created:
            created += 1
    return HttpResponse(json.dumps({'success': True, 'count': created}), content_type='application/json')

@csrf_exempt
@require_http_methods(["GET"])
def avatar_preview(request, user_id):
    """
    头像预览页面 - 专用于显示头像图片
    GET /xiangsu/avatar/preview/<user_id>/
    """
    try:
        profile = UserProfile.objects.get(user_id=user_id)
        user_info = profile.get_user_info()
        
        if user_info['avatar']:
            html_content = f"""
            <!DOCTYPE html>
            <html>
            <head>
                <title>头像预览 - {user_info['username']}</title>
                <style>
                    body {{
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        height: 100vh;
                        margin: 0;
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    }}
                    .avatar-container {{
                        text-align: center;
                        background: white;
                        padding: 30px;
                        border-radius: 15px;
                        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                    }}
                    .avatar-img {{
                        width: 200px;
                        height: 200px;
                        border-radius: 50%;
                        object-fit: cover;
                        border: 5px solid #4CAF50;
                    }}
                    .user-info {{
                        margin-top: 15px;
                        color: #333;
                    }}
                </style>
            </head>
            <body>
                <div class="avatar-container">
                    <img src="{user_info['avatar']}" alt="{user_info['username']}的头像" class="avatar-img">
                    <div class="user-info">
                        <h2>{user_info['username']}</h2>
                        <p>头像预览</p>
                    </div>
                </div>
            </body>
            </html>
            """
        else:
            html_content = """
            <!DOCTYPE html>
            <html>
            <head>
                <title>暂无头像</title>
                <style>
                    body {{
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        height: 100vh;
                        margin: 0;
                        background: #f5f5f5;
                    }}
                    .no-avatar {{
                        text-align: center;
                        background: white;
                        padding: 40px;
                        border-radius: 10px;
                        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                    }}
                </style>
            </head>
            <body>
                <div class="no-avatar">
                    <h2>该用户暂无头像</h2>
                    <p>请上传头像后再查看预览</p>
                </div>
            </body>
            </html>
            """
        
        return HttpResponse(html_content)
    except UserProfile.DoesNotExist:
        return HttpResponse('<h1>用户不存在</h1>', status=404)


@login_required
def admin_tasks_management(request):
    """每日任务管理页面 GET /xiangsu/admin/tasks/"""
    if not request.user.is_staff:
        return HttpResponse('<h1>无权限</h1>', status=403)
    
    date = request.GET.get('date') or ''
    from django.utils import timezone
    from zoneinfo import ZoneInfo
    
    # 统一使用 Asia/Shanghai 时区
    shanghai_tz = ZoneInfo('Asia/Shanghai')
    now_shanghai = timezone.now().astimezone(shanghai_tz)
    
    try:
        if date:
            dt = timezone.datetime.strptime(date, '%Y-%m-%d').date()
        else:
            dt = now_shanghai.date()
    except Exception:
        dt = now_shanghai.date()

    tasks = Task.objects.all().order_by('id')
    assigned_ids = set(TaskAssignment.objects.filter(date=dt).values_list('task_id', flat=True))

    html = [
        "<!DOCTYPE html>",
        "<html lang='zh-CN'>",
        "<head>",
        "<meta charset='UTF-8'>",
        "<title>每日任务管理</title>",
        "<style>",
        "body{font-family:Arial,sans-serif;background:#f5f5f5;margin:0;padding:20px}",
        ".container{max-width:1000px;margin:0 auto;background:#fff;padding:20px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1)}",
        ".header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}",
        ".grid{display:grid;grid-template-columns:40px 60px 260px 80px 80px 80px 120px;gap:8px;align-items:center}",
        ".row{padding:8px 0;border-bottom:1px solid #eee}",
        ".btn{padding:6px 10px;border:none;border-radius:6px;cursor:pointer}",
        ".primary{background:#10B981;color:#fff}",
        ".ghost{background:#F3F4F6;color:#374151}",
        "input[type='checkbox']{width:18px;height:18px;cursor:pointer}",
        "</style>",
        "</head>",
        "<body>",
        "<div class='container'>",
        f"<div class='header'><h2>每日任务管理</h2><div>日期：<input id='date' type='date' value='{dt}'/> <button class='btn ghost' onclick='reload()'>查看</button> <button class='btn primary' onclick='publish()'>发布选中任务到当日</button></div></div>",
        "<div class='grid' style='font-weight:600'><div><input type='checkbox' id='selectAll' onclick='toggleAll(this)'></div><div>ID</div><div>任务</div><div>积分</div><div>目标</div><div>每日</div><div>当前是否发布</div></div>",
    ]
    for t in tasks:
        is_published = t.id in assigned_ids or t.daily
        html += [
            "<div class='grid row'>",
            f"<div><input type='checkbox' class='task-check' value='{t.id}'></div>",
            f"<div>{t.id}</div>",
            f"<div>{t.title}</div>",
            f"<div>{t.points}</div>",
            f"<div>{t.target}</div>",
            f"<div>{'是' if t.daily else '否'}</div>",
            f"<div>{'是' if is_published else '否'}</div>",
            "</div>",
        ]
    html += [
        "</div>",
        "<script>",
        "function reload(){const d=document.getElementById('date').value;location.href='?date='+encodeURIComponent(d)}",
        "function toggleAll(source){const checkboxes=document.querySelectorAll('.task-check');for(let i=0;i<checkboxes.length;i++){checkboxes[i].checked=source.checked}}",
        "function publish(){",
        "  const d=document.getElementById('date').value;",
        "  const checkboxes=document.querySelectorAll('.task-check:checked');",
        "  const ids=[];",
        "  for(let i=0;i<checkboxes.length;i++){ids.push(parseInt(checkboxes[i].value))}",
        "  if(ids.length===0){if(!confirm('未选择任何任务。确定要仅发布默认每日任务吗？')){return}}",
        "  fetch('/xiangsu/admin/tasks/publish/',{",
        "    method:'POST',",
        "    credentials:'same-origin',",
        "    headers:{'Content-Type':'application/json'},",
        "    body:JSON.stringify({date:d, task_ids:ids})",
        "  }).then(r=>r.json()).then(d=>{",
        "    if(d.success){alert('已发布 ' + d.count + ' 个任务');location.reload()}",
        "    else{alert('失败:'+d.message)}",
        "  }).catch(e=>alert('错误:'+e))",
        "}",
        "</script>",
        "</body>",
        "</html>",
    ]
    return HttpResponse(''.join(html))


@csrf_exempt
@require_http_methods(["POST"])
@login_required
def admin_publish_daily_tasks(request):
    """发布每日任务：将选中的任务（或所有active且daily的任务）发布到指定日期"""
    if not request.user.is_staff:
        return HttpResponse(json.dumps({'success': False, 'message': '无权限'}), content_type='application/json', status=403)
    try:
        payload = json.loads(request.body or '{}')
        date = payload.get('date')
        task_ids = payload.get('task_ids')
        
        from django.utils import timezone
        from zoneinfo import ZoneInfo
        
        # 统一使用 Asia/Shanghai 时区
        # 如果前端传来的 date 只是 'YYYY-MM-DD'，strptime 默认是 00:00:00
        # 但我们只需要 date 对象，所以时区影响主要在于 'today' 的判断
        # 这里直接解析日期字符串即可
        dt = timezone.datetime.strptime(date, '%Y-%m-%d').date() if date else timezone.now().astimezone(ZoneInfo('Asia/Shanghai')).date()
        
        count = 0
        
        if task_ids is not None:
            # 如果明确传递了 task_ids (即使是空列表)，则只发布这些
            # 注意：如果用户想"取消发布"，目前逻辑只能增加发布。
            # 如果要支持完全同步（删除未选中的），逻辑会复杂些。
            # 这里假设"发布"是增量操作。
            # 但为了让用户能"控制"今日任务，也许应该只发布选中的？
            # 如果列表中包含非 daily 的任务，它们会被添加。
            # daily=True 的任务默认会显示，除非我们修改 views logic。
            # 但我们不动 views logic。
            
            # 我们只处理 TaskAssignment
            # 如果 task_ids 为空，且用户确认了，可能意图是只保留 daily 任务？
            # 但 admin_publish_daily_tasks 目前是 create TaskAssignment.
            
            tasks_to_assign = Task.objects.filter(id__in=task_ids, active=True)
            for t in tasks_to_assign:
                _, created = TaskAssignment.objects.get_or_create(date=dt, task=t)
                if created:
                    count += 1
        else:
            # 旧逻辑：发布所有 daily=True 的任务
            base_qs = Task.objects.filter(active=True, daily=True)
            for t in base_qs:
                _, created = TaskAssignment.objects.get_or_create(date=dt, task=t)
                if created:
                    count += 1
                    
        return HttpResponse(json.dumps({'success': True, 'date': str(dt), 'count': count}), content_type='application/json')
    except Exception as e:
        return HttpResponse(json.dumps({'success': False, 'message': str(e)}), content_type='application/json', status=500)
